package com.xmy.cultivate.controller;
import com.lkl.laop.sdk.Config;
import com.lkl.laop.sdk.LKLSDK;
import com.lkl.laop.sdk.exception.SDKException;
import com.xmy.cultivate.entity.Admin;
import com.xmy.cultivate.entity.Company;
import com.xmy.cultivate.entity.Staff;
import com.xmy.cultivate.enums.SourseLeveEnum;
import com.xmy.cultivate.enums.StatusStaffEnum;
import com.xmy.cultivate.service.ICompanyService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class BaseController {

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected Long companyId = 1L;
    protected Long adminId;
    protected String companyName;
    protected Integer isSuper;
    protected Admin adminModel;

    protected Staff staffInfo;

    protected StatusStaffEnum statusStaffEnum = StatusStaffEnum.NO;

    protected SourseLeveEnum sourseLeveEnum;

    protected Integer sourseLeve;

    /**
     * 学生分班是否需要分层，1是，0否
     */
    protected Integer gradeHierarchy;

    //管辖校区
    protected List<Long> baseSchoolIdList = new ArrayList<>();
    protected String baseSchoolIdStr = "";
    protected List<Long> roleList = new ArrayList<>();
    List<String> permissionCodeList = new ArrayList<>();

    @Autowired
    ICompanyService iCompanyService;

    @Value("${systype.name}")
    private String systype; // 拉卡拉appId

    /****************************************拉卡拉开始********************************************/
    @Value("${lkl.appId}")
    private String appIdYml; // 拉卡拉appId

    @Value("${lkl.serialNo}")
    private String serialNoYml; // 你的证书序列号


    @Value("${lkl.appId}")
    private String appId; // 拉卡拉appId

    @Value("${lkl.serialNo}")
    private String serialNo;

    /**
     * 	服务地址
     */
    @Value("${lkl.serverUrl}")
    private String serverUrl;

    /**
     * 拉卡拉报文加密对称性密钥
     */
    @Value("${lkl.sm4Key}")
    private String sm4Key;

    /**
     * 商户私钥信息地址
     */
    //private static final String priKeyPath = "lkl-zf-bs-laop-java-sdk-sample/src/main/resources/OP00000003商户私钥.txt";
    private String priKeyPath = "";
    /**
     * 拉卡拉支付平台证书地址
     */
    //private static final String lklCerPath = "lkl-zf-bs-laop-java-sdk-sample/src/main/resources/lakala开放平台证书.cer";
    private String lklCerPath = "";
    /**
     * 拉卡拉支付平台证书地址2(用于拉卡拉通知验签)
     */
    private String lklNotifyCerPath = "";

    private static volatile boolean init = false;
    /*****************************************************拉卡拉结束*************************************************************/

    //protected Claims claims;

    //使用jwt方式获取
//    @ModelAttribute
//    public void setResAnReq(HttpServletRequest request,HttpServletResponse response) {
//        this.request = request;
//        this.response = response;
//
//        Object obj = request.getAttribute("user_claims");
//
//        if(obj != null) {
//            this.claims = (Claims) obj;
//            this.companyId = (String)claims.get("companyId");
//            this.companyName = (String)claims.get("companyName");
//        }
//    }

    //使用shiro获取
    @ModelAttribute
    public void setResAnReq(HttpServletRequest request,HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.companyId = 1L;


        this.appId = this.appIdYml;
        this.serialNo = this.serialNoYml;
        if (systype.equals("dev")){
            //测试环境
            this.priKeyPath = this.getClass().getClassLoader().getResource("OP00000003_private_key.pem").getPath();
            this.lklCerPath = this.getClass().getClassLoader().getResource("lkl-apigw-v2.cer").getPath();
            this.lklNotifyCerPath = this.getClass().getClassLoader().getResource("lkl-apigw-v2.cer").getPath();
        }else {
            this.priKeyPath = "/www/wwwroot/erp/admin/cer/OP00000003_private_key.pem";
            this.lklCerPath = "/www/wwwroot/erp/admin/cer/lkl-apigw-v1.cer";
            this.lklNotifyCerPath = "/www/wwwroot/erp/admin/cer/lkl-apigw-v1.cer";
        }



        //获取session中的安全数据
        Subject subject = SecurityUtils.getSubject();
        //1.subject获取所有的安全数据集合
        PrincipalCollection principals = subject.getPrincipals();
        if(principals != null && !principals.isEmpty()){
            //2.获取安全数据
            Admin admin = (Admin) principals.getPrimaryPrincipal();
            this.staffInfo = admin.getStaffInfo();
            this.adminId = admin.getId();
            this.adminModel = admin;
            this.baseSchoolIdList = admin.getSchoolIdList();
            this.baseSchoolIdStr = String.join(",", this.baseSchoolIdList.stream().map(String::valueOf).collect(Collectors.toList()));
            if(this.baseSchoolIdStr.isEmpty()){
                this.baseSchoolIdStr = "0";
            }
            this.isSuper = admin.getIsSuper();
            this.roleList = admin.getRoleIdList();
            this.permissionCodeList = admin.getPermissionCodeList();
            if (admin.getIsSuper().equals(1)){
                this.statusStaffEnum = StatusStaffEnum.IN;
                this.sourseLeveEnum = SourseLeveEnum.ALL;
                this.sourseLeve = 1;
            }else {
                if (this.staffInfo != null){
                    this.statusStaffEnum = this.staffInfo.getStatus();
                }
                this.sourseLeveEnum = admin.getSourseLeve();
                if ( this.sourseLeveEnum.equals(SourseLeveEnum.ONESELF)){
                    this.sourseLeve =2;
                }else {
                    this.sourseLeve = 1;
                }
            }

            Company company = iCompanyService.getById(this.companyId);
            if (company != null){
                this.gradeHierarchy = company.getGradeHierarchy();
            }

            //System.out.println();
            //System.out.print("admin");

            //System.out.print( this.adminModel);
            //System.out.println();

            //System.out.print(admin);
            /*ProfileResult result = (ProfileResult)principals.getPrimaryPrincipal();
            this.companyId = result.getCompanyId();
            this.companyName = result.getCompany();
            this.userId = result.getUserId();
            System.out.println(companyId);*/
        }
    }

    /***
     * @Description: 初始化设置商户公共参数（全局只需设置一次）
     * @throws Exception
     */
    public void doInit() throws Exception {
        if(!init) {
            init = initByJava();
        }
        //init = initByJava();
    }

    public boolean initByJava() throws SDKException {
        Config config = new Config();
        config.setAppId(appId);
        config.setSerialNo(serialNo);
        config.setPriKeyPath(priKeyPath);
        config.setLklCerPath(lklCerPath);
        config.setLklNotifyCerPath(lklNotifyCerPath);
        config.setServerUrl(serverUrl);
        config.setSm4Key(sm4Key);
        return LKLSDK.init(config);

    }

}
